package com.atguigu.comment.controller;

import com.atguigu.comment.client.CommentClient;
import com.atguigu.comment.entity.EduComment;
import com.atguigu.comment.service.EduCommentService;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;

import com.atguigu.commonutils.vo.UcenterMemberVo;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2024-12-18
 */
@Api(description = "评论管理")
@RestController
@RequestMapping("/comment/comment")
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;
    @Autowired
    private CommentClient commentClient;

    //根据课程id查询评论列表
    @ApiOperation(value = "评论分页列表")
    @GetMapping("getCommentInfo/{page}/{limit}")
    public R getCommentInfo(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "courseQuery", value = "查询对象", required = false)
            String courseId) {
        Page<EduComment> commentPage = new Page<>(page, limit);
        Map<String, Object> map = commentService.getCouseCommentByCourseId(courseId, commentPage);
        return R.ok().data(map);
    }

    @ApiOperation("添加评论")
    @PostMapping("addEduComment")
    public R addEduComment(HttpServletRequest request, @RequestBody EduComment eduComment) {
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        //判断是否登录
        if(StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"请先登录");
        }

        eduComment.setMemberId(memberId);

        //远程调用CommentClient根据用户id获取用户信息
        UcenterMemberVo memberVo = commentClient.getMemberInfoById(memberId);
        eduComment.setAvatar(memberVo.getAvatar());
        eduComment.setNickname(memberVo.getNickname());
        eduComment.setGmtCreate(memberVo.getGmtCreate());
        eduComment.setGmtModified(memberVo.getGmtModified());

        //保存评论
        commentService.save(eduComment);
        return R.ok();
    }

}

